// pages/chat/chat.js
import { getUserInfo } from '../../api/user'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    toView: '',//控制上滑距离
    userInfo: {},
    msgList: [], // 消息列表
    message: '', // 消息
    cursor: 0,// 光标位置
    hideEmoji: true,
    emojiList: ['😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😉', '😊', '😋', '😎', '😍', '😘', '🥰', '😗', '😙', '😚', '🙂', '🤗', '🤩', '🤔', '🤨', '😐', '😑', '😶', '🙄', '😏', '😣', '😥', '😮', '🤐', '😯', '😪', '😫', '🥱', '😴', '😌', '😛', '😜', '😝', '🤤', '😒', '😓', '😔', '😕', '🙃', '🤑', '😲', '☹️', '🙁', '😖', '😞', '😟', '😤', '😢', '😭', '😦', '😧', '😨', '😩', '🤯', '😬', '😮‍💨', '😰', '😱', '🥵', '🥶', '😳', '🤪', '😵', '😵‍💫', '🥴', '😠', '😡', '🤬', '😷', '🤒', '🤕', '🤢', '🤮', '😇', '🥳', '🥺', '🤠', '🤡', '🤥', '🤫', '🤭', '🧐', '🤓', '😈', '👹', '👺', '💀', '☠️', '👻', '👽', '👾', '🤖', '💩', '😺', '😸', '😹', '😻', '😼'],
  },
  async onLoad() {
    const token = wx.getStorageSync('token')
    if (token) {
      await this.getUserInfoData()
      // socket连接到服务器
      await this.connectToWsServer()
    } else {
      wx.redirectTo({
        url: '/subpkg/login/login',
      })
    }
  },
  async getUserInfoData() {
    const res = await getUserInfo()
    this.setData({
      userInfo: res.data
    })
  },
  // 连接到ws服务器
  connectToWsServer() {
    this.socket = wx.connectSocket({
      // url: 'wss://localhost:3002/api/chat/connect?room=30908286-466b-485e-b673-332db053bd10&id=user_b7d8955c-8339-458e-a13b-461b1271e5d4&type=group'
      url: `ws://47.113.110.139:3001/api/chat/connect?room=30908286-466b-485e-b673-332db053bd10&id=${this.data.userInfo.userid}&type=group`
    })

    // 连接服务器成功
    this.socket.onOpen(res => {
      console.log('---连接服务器成功---')
    })

    // 接收到服务器返回的消息
    this.socket.onMessage(msg => {
      if (msg) {
        const obj = JSON.parse(msg.data)
        console.log('---obj---', obj)
        if (obj.type === 'list') {
          this.setData({
            msgList: obj.historyMsgList
          }, () => {
            this.setData({
              toView: `msg-${obj.historyMsgList.length - 1}`
            })
          })
        } else if (obj.type === 'other') {
          if (obj.data.sender_id === this.data.userInfo.userid) return

          this.setData({
            msgList: [...this.data.msgList, obj.data],
            toView: `msg-${this.data.msgList.length}`
          })
        }
      }
    })
  },
  handleChange(e) {
    this.setData({
      message: e.detail.value
    })
  },
  // 发消息给服务器
  send() {
    if (this.data.message.trim().length === 0) {
      wx.showToast({
        title: '内容不能为空',
        icon: 'none'
      })
      return
    }
    // 更新视图
    this.setData({
      msgList: [...this.data.msgList, {
        "content": this.data.message,
        "created_at": new Date() - 0,
        "file_size": 0,
        "media_type": "text",
        "receiver_id": "8d0413fd-ee0c-41ab-9812-bd52dcf12fec",
        "room": "30908286-466b-485e-b673-332db053bd10",
        "sender_id": this.data.userInfo.userid,
        "status": 1,
        "type": "group",
        "updated_at": new Date() - 0,
        "avatar": this.data.userInfo.avatar,
        "nickname": this.data.userInfo.nickname
      }],
      toView: `msg-${this.data.msgList.length}`
    })
    // 发送给服务器
    this.socket && this.socket.send({
      data: JSON.stringify({
        "content": this.data.message,
        "created_at": new Date(),
        "file_size": 0,
        "media_type": "text",
        "receiver_id": "8d0413fd-ee0c-41ab-9812-bd52dcf12fec",
        "room": "30908286-466b-485e-b673-332db053bd10",
        "sender_id": this.data.userInfo.userid,
        "status": 1,
        "type": "group",
        "updated_at": new Date(),
        "avatar": this.data.userInfo.avatar,
        "nickname": this.data.userInfo.nickname
      })
    })

    // 清空表单内容
    this.setData({
      message: ''
    })
  },
  // 切换emoji显示和隐藏
  toggleEmoji() {
    this.setData({
      hideEmoji: !this.data.hideEmoji
    })
  },
  handleBlur(e) {
    this.data.cursor = e.detail.cursor
  },
  chooseEmoji(e) {
    const index = e.target.dataset.index

    // 计算插入的位置
    /**
    if (this.data.message.trim().length > 0) {
      const firstParagraph = this.data.message.substr(0,this.data.cursor)
      const lastParagraph = this.data.message.substr(this.data.cursor,this.data.message.trim().length)
      
      this.setData({
        message: `${firstParagraph}${this.data.emojiList[index]}${lastParagraph}`
      })
    } else {
      this.setData({
        message: `${this.data.message}${this.data.emojiList[index]}`
      })
    }
     */
    this.setData({
      message: `${this.data.message}${this.data.emojiList[index]}`
    })
  },
  closeEmoji() {
    this.setData({
      hideEmoji: true
    })
  },
  // 上传图片
  upload() {
    wx.chooseImage({
      success: (res) => {
        const tempFilePaths = res.tempFilePaths
        // 上传图片
        wx.uploadFile({
          url: 'https://huangjiangjun.top:3002/admin/file/chats/upload', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          success: res2 => {
            if (res2.data) {
              const resObj = JSON.parse(res2.data)
              this.setData({
                msgList: [...this.data.msgList, {
                  "content": resObj.fileUrl,
                  "created_at": new Date() - 0,
                  "file_size": 0,
                  "media_type": "image",
                  "receiver_id": "8d0413fd-ee0c-41ab-9812-bd52dcf12fec",
                  "room": "30908286-466b-485e-b673-332db053bd10",
                  "sender_id": this.data.userInfo.userid,
                  "status": 1,
                  "type": "group",
                  "updated_at": new Date() - 0,
                  "avatar": this.data.userInfo.avatar,
                  "nickname": this.data.userInfo.nickname
                }],
                toView: `msg-${this.data.msgList.length}`
              })

              this.socket && this.socket.send({
                data: JSON.stringify({
                  "content": resObj.fileUrl,
                  "created_at": new Date(),
                  "file_size": 0,
                  "media_type": "image",
                  "receiver_id": "8d0413fd-ee0c-41ab-9812-bd52dcf12fec",
                  "room": "30908286-466b-485e-b673-332db053bd10",
                  "sender_id": this.data.userInfo.userid,
                  "status": 1,
                  "type": "group",
                  "updated_at": new Date(),
                  "avatar": this.data.userInfo.avatar,
                  "nickname": this.data.userInfo.nickname
                })
              })
            }
          },
          fail: err => {
            console.log('---err---', err)
          }
        })
      }
    })
  },
  priview(e) {
    const image = e.target.dataset.image
    wx.previewImage({
      urls: [image]
    })
  }
})